package com.shoute.ai.utils;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class RedisChatHistoryService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    // 添加聊天ID（自动去重）
    public void addChatId(String type, String chatId) {
        redisTemplate.opsForSet().add(buildKey(type), chatId);
    }

    // 获取所有聊天ID（等效于 getOrDefault）
    public List<String> getChatIds(String type) {
        Set<String> members = redisTemplate.opsForSet().members(buildKey(type));
        return members != null ? new ArrayList<>(members) : Collections.emptyList();
    }

    // 检查聊天ID是否存在
    public boolean containsChatId(String type, String chatId) {
        return Boolean.TRUE.equals(
                redisTemplate.opsForSet().isMember(buildKey(type), chatId)
        );
    }

    // 删除特定聊天ID
    public void removeChatId(String type, String chatId) {
        redisTemplate.opsForSet().remove(buildKey(type), chatId);
    }

    // 删除整个聊天类型
    public void deleteChatType(String type) {
        redisTemplate.delete(buildKey(type));
    }

    // 获取所有聊天类型
    public Set<String> getAllChatTypes() {
        return redisTemplate.keys("chatHistory:*").stream()
                .map(key -> key.substring("chatHistory:".length()))
                .collect(Collectors.toSet());
    }

    private String buildKey(String type) {
        return "chatHistory:" + type;
    }
}
